import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.io.HttpsConnection;

public class PostingThread extends Thread {

	private ClickSMS myCaller;
	private String myURL;
	private boolean myIsSms;
	
	public PostingThread(ClickSMS caller, String url, boolean isSms) {
		myCaller = caller;
		myURL = url;
		myIsSms = isSms;
	}
	
	public void run() {
		String result;
		try {
			result = httpPost();
		} catch (Exception e) {
			result = e.toString();
		}
		myCaller.notifyPostResult(result, myIsSms);
		//Remove link to caller so this object can be garbage collected
		myCaller = null;
	}

	private String httpPost() throws IOException {
		HttpsConnection c = null;
		InputStream is = null;
		OutputStream os = null;
		StringBuffer b = new StringBuffer();
		try {
			c = (HttpsConnection) Connector.open(myURL);
			c.setRequestMethod(HttpConnection.POST);
			c.setRequestProperty("User-Agent", "Profile/MIDP-1.0 Configuration/CLDC-1.0");
			c.setRequestProperty("Content-Language", "en-US");
			os = c.openOutputStream();

			// start
			String str = "";
			byte postmsg[] = str.getBytes();
			for (int i = 0; i < postmsg.length; i++) {
				os.write(postmsg[i]);
			}
			os.flush();
			// end

			is = c.openDataInputStream();
			int ch;
			while ((ch = is.read()) != -1) {
				b.append((char) ch);
				System.out.println((char) ch);
			}
			return b.toString();
		} finally {
			if (is != null) {
				is.close();
			}
			if (os != null) {
				os.close();
			}
			if (c != null) {
				c.close();
			}
		}
	}
}
